import { REG_EXP } from '@/constants'
import { MinusCircleOutlined, PlusCircleOutlined } from '@ant-design/icons'
import { styled, Access } from '@umijs/max'
import { Input, Modal, TimePicker, message } from 'antd'
import dayjs, { Dayjs } from 'dayjs'
import { useState } from 'react'

type Value = Record<string, string>
interface ManagerInfoProps {
  value?: Value
  onChange?: (val: Value) => void
}

const Container = styled.div`
  width: max-content;
  border-radius: 8px;
  background: #f5f5f5;
  padding: 0 16px;
`
const Item = styled.div`
  width: 100%;
  height: 32px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #eeeeee;

  .label {
    width: 100px;
  }

  .value {
    width: 100px;
  }
`
const Add = styled.div`
  width: 100%;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
`
const format = 'HH:mm'

const ManagerInfo: React.FC<ManagerInfoProps> = (props) => {
  const [open, setOpen] = useState(false)
  const [startTime, setStartTime] = useState('')
  const [endTime, setEndTime] = useState<Dayjs>()
  const [telephone, setTelephone] = useState<string>('')

  const keys = Object.keys(props.value || {})

  const getStartTime = (time: string) => {
    const _time = time.split(':')
    let _hour = parseInt(_time[0])
    let _minute = parseInt(_time[1]) + 1
    if (_minute === 60) {
      return `${String(_hour + 1).padStart(2, '0')}:00`
    }
    return `${String(_hour).padStart(2, '0')}:${String(_minute).padStart(2, '0')}`
  }

  const remove = (key: string) => {
    delete props.value![key]
    props.onChange?.({...props.value})
  }

  const addRow = () => {
    if (keys.length && keys.at(-1)?.endsWith('23:59')) {
      message.info('已无可分配时间')
      return
    }
    setOpen(true)
    setTelephone('')
    setStartTime(keys.length ? getStartTime(keys.at(-1)!.split('-')[1]) : '00:00')
    setEndTime(dayjs('23:59', format))
  }

  const onCancel = () => {
    setOpen(false)
  }

  const onOk = () => {
    if (!REG_EXP.NUMBER.test(telephone)) {
      message.error('请输入手机号')
    } else {
      const _value = {...props.value}
      _value[`${startTime}-${endTime?.format(format)}`] = telephone
      props.onChange?.(_value)
      onCancel()
    }
  }

  const setDisableTime = (val: Dayjs, _keys: string[]) => {
    if (_keys.length < 1) {
      return {}
    }
    const _lastKey = _keys.at(-1)!
    const _time = _lastKey.split('-')[1].split(':')
    let _hour = parseInt(_time[0])
    let _minute = parseInt(_time[1]) + 1
    if (_minute >= 60) {
      _hour += 1
      _minute = 0
    }
    const disabledHours: number[] = []
    const disabledMinutes: number[] = []
    for (let i=0; i<_hour; i++) {
      disabledHours.push(i)
    }
    for (let i=0; i<60; i++) {
      disabledMinutes.push(i)
    }
    return {
      disabledHours: () => disabledHours,
      disabledMinutes: (hour: number) => {
        if (hour < _hour) return disabledMinutes
        if (hour === _hour) {
          return disabledMinutes.filter(i => i < _minute)
        }
        return []
      }
    }
  }

  return <Container>
    {
      keys.map((key) => {
        return <Item key={key}>
          <div className="label">{ key }</div>
          <div className='value'>{ props.value![key] }</div>
          <Access accessible={key === keys.at(-1)}>
            <MinusCircleOutlined style={{color: 'red', cursor: 'pointer'}} onClick={() => remove(key)} />
          </Access>
        </Item>
      })
    }
    <Add onClick={addRow}>
      <PlusCircleOutlined style={{color: 'green'}} />
      <div style={{marginLeft: 8}}>添加联系方式</div>
    </Add>
    <Modal
      title='联系方式'
      open={open}
      onCancel={onCancel}
      onOk={onOk}
    >
      <div>时间段</div>
      <div style={{display: 'flex', alignItems: 'center', gap: 16, marginTop: 8}}>
        <div style={{borderRadius: 8, background: '#f5f5f5', lineHeight: '32px', padding: '0 16px'}}>{ startTime }</div>
        <div>{` - `}</div>
        <TimePicker
          format={format}
          value={endTime}
          onChange={setEndTime}
          disabledTime={val => setDisableTime(val, keys)}
          allowClear={false}
        />
      </div>
      <div style={{marginTop: 8}}>手机号</div>
      <Input style={{marginTop: 8}} placeholder='请输入人手机号' value={telephone} onChange={({target}) => setTelephone(target.value)} />
    </Modal>
  </Container>
}

export default ManagerInfo